﻿using System;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Authentication.Live;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Services;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
namespace Eneta.Portal.Authentication.Pages
{
    public class RegisterPage : Page
    {
        protected TextBox displayNameField;
        protected Label lblDisplayNameError;
        protected TextBox emailField;
        protected Label lblEmailError;
        protected Button butSubmit;

        protected HtmlGenericControl warningBox;
        protected string redir;
        protected HtmlControl userBlock;
        protected HtmlControl passwordBlock;

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.butSubmit.Click += new EventHandler(Submit_Click);
        }
        #endregion
        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            warningBox.Visible = false;
            redir = Request.QueryString["Source"];

            if (redir == null)
            {
                redir = SPContext.Current.Web.Url;
            }

            if (User.Identity.IsAuthenticated)
            {
                if (!IsPostBack)
                {
                    var bup = BlogUserProfile.GetUser(User.Identity.Name);

                    if (bup != null)
                    {
                        Logger.LogInfo("AUTH: Profile found", "");
                        displayNameField.Text = bup.DisplayName;
                        emailField.Text = bup.Email;
                    }
                    else
                    {
                        Logger.LogInfo("AUTH: Profile is null", "");
                        Response.Redirect(redir);
                    }
                }
            }
            else
            {
                Logger.LogInfo("AUTH: No user", "");
                Response.Redirect(redir);
            }
        }

        public void Submit_Click(Object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(displayNameField.Text))
            {
                userBlock.Attributes["class"] = "info-row failed-info";
                lblDisplayNameError.Text = Resources.EnetaAuth.UserNameIsMissing;
                lblDisplayNameError.Visible = true;
                warningBox.Visible = true;
                return;
            }
            if (!Regex.IsMatch(displayNameField.Text, "^[a-zA-Z0-9]{4,15}$"))
            {
                userBlock.Attributes["class"] = "info-row failed-info";
                lblDisplayNameError.Text = Resources.EnetaAuth.UserNameIsInvalid;
                lblDisplayNameError.Visible = true;
                warningBox.Visible = true;
                return;
            }
            using (var site = new SPSite(SPContext.Current.Web.Site.ID))
            {
                using (var web = site.OpenWeb())
                {
                    var queryString = @"<Where><Eq><FieldRef Name=""Title"" /><Value Type=""Text"">{0}</Value></Eq></Where>";
                    queryString = string.Format(queryString, displayNameField.Text);

                    var list = web.Lists["ProfileList"];
                    var query = new SPQuery();
                    query.Query = queryString;

                    var results = list.GetItems(query);
                    if (results != null)
                        if (results.Count > 0)
                        {
                            userBlock.Attributes["class"] = "info-row failed-info";
                            lblDisplayNameError.Text = Resources.EnetaAuth.UserNameIsAlreadyTaken;
                            lblDisplayNameError.Visible = true;
                            warningBox.Visible = true;
                            return;
                        }
                }
            }
            userBlock.Attributes["class"] = "info-row";

            if (string.IsNullOrEmpty(emailField.Text))
            {
                passwordBlock.Attributes["class"] = "info-row failed-info";
                lblEmailError.Text = Resources.EnetaAuth.EmailIsMissing;
                lblEmailError.Visible = true;
                warningBox.Visible = true;
                return;
            }
            if (!Regex.IsMatch(emailField.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
            {
                passwordBlock.Attributes["class"] = "info-row failed-info";
                lblEmailError.Text = Resources.EnetaAuth.EmailIsIncorrect;
                lblEmailError.Visible = true;
                warningBox.Visible = true;
                return;
            }

            if (!User.Identity.IsAuthenticated)
                return;

            var profileId = 0;

            try
            {
                var siteId = SPContext.Current.Site.ID;
                var sec = new SPSecurity.CodeToRunElevated(
                    delegate
                        {
                            var bup = BlogUserProfile.GetUser(User.Identity.Name);
                            bup.DisplayName = displayNameField.Text;
                            bup.Email = emailField.Text;
                            bup.Update();

                            profileId = bup.ItemId;
                            var name = User.Identity.Name;

                            var site = new SPSite(siteId);
                            var web = site.OpenWeb();
                            AddNewSpUser(web,name,emailField.Text, displayNameField.Text);

                            var userMail = emailField.Text;
                            //var body = "<html><body><p>Tere " + displayNameField.Text + ",</p>";
                            //body += "<p>Liitusite edukalt ENETA portaaliga.</p>";
                            //body += "<p>Tervitustega,<br/>";
                            //body += "ENETA meeskond</p></body></html>";
                            var profileLink = "http://www.eneta.ee/profile.aspx?ID=" + profileId;
                            //var body = "<html><body style=\"font-family:arial;font-size:10pt;\"><p>Hei " + displayNameField.Text + "!</p>";
                            //body += "<p>Oled edukalt liitunud Eneta kommuuniga ja meil on Sulle palju ";
                            //body += "erinevaid võimalusi kaasalöömiseks:<p>";
                            //body += "<ul>";
                            //body += "<li><a href=\"http://www.eneta.ee/addblog.aspx\">Lisa oma blogi</a> ja kõik Sinu Microsofti teemalised postitused ilmuvad Enetas</li>";
                            //body += "<li><a href=\"http://www.eneta.ee/uudised/teated/addannouncement.aspx\">Lisa uudiseid</a> või huvitavaid Microsoftiga seotud leide teadete rubriiki</li>";
                            //body += "<li><a href=\"http://www.eneta.ee/foorum/lehed/default.aspx\">Foorumis</a> saad esitada Microsofti puudutavaid küsimusi või abistada teisi kommuuni liikmeid</li>";
                            //body += "<li>Ja veel palju muud põnevat. Tutvu võimalustega oma kasutajaprofiili lehel ";
                            //body += "<a href=\"" + profileLink + "\">" + profileLink + "</a></li>";
                            //body += "</ul>";

                            //body += "<p>Tervitustega,<br/>";
                            //body += "Eneta tiim</p>";
                            //body += "<a href=\"http://www.eneta.ee\"><img src=\"http://www.eneta.ee/SiteCollectionImages/logod/eneta_logo_250x78_sinine.png\" border=\"0\"></a>";
                            //body += "</body></html>";

                            //try
                            //{
                            //    SPUtility.SendEmail(web, false, false, userMail, displayNameField.Text + ", teretulemast Eneta portaali liikmeks!", body);
                            //    SPUtility.SendEmail(web, false, false, "abi@eneta.ee", displayNameField.Text + ", teretulemast Eneta portaali liikmeks!", body);
                            //}
                            //catch(Exception ex)
                            //{
                            //    Logger.LogException(ex);
                            //}

                            var mailer = new MailerService();
                            var addresses = new[] { userMail, "abi@eneta.ee" };
                            mailer.SendMailByTemplate("WelcomeMessage", displayNameField.Text, displayNameField.Text, profileLink, addresses);


                            web.Close();
                            web.Dispose();
                            site.Dispose();
                        });
                SPSecurity.RunWithElevatedPrivileges(sec);
            }
            catch(Exception ex)
            {
                Logger.LogException(ex);
                return;
            }
            //Response.Redirect(Request.QueryString["Source"]);
            Response.Redirect("/Lehed/editprofile.aspx?profileID=" + profileId + "&msg=joined", false);
        }
        private static void AddNewSpUser(SPWeb web, string userName, string email, string name)
        {
            var site = web.Site;

            try
            {
                site.AllowUnsafeUpdates = true;
                web.AllowUnsafeUpdates = true;

                Logger.LogInfo("AddNewSpUser(): Adding role assignment for reader role", "RegisterPage");
                var user = web.EnsureUser("liveid:" + userName);
                user.Email = email;
                user.Name = name;
                user.Update();

                try
                {
                    Logger.LogInfo("AddNewSpUser(): Removing default role assignments", "RegisterPage");
                    web.RoleAssignments.Remove(user);
                    web.Update();
                }
                catch(Exception ex)
                {
                    Logger.LogInfo("AddNewSpUser(): Error removing user role assignments", "RegisterPage");
                    Logger.LogException(ex);
                }

                Logger.LogInfo("AddNewSpUser(): Adding user to visitors group", "RegisterPage");
                var group = web.SiteGroups["Eneta Portal külastajat"];
                group.AddUser(user);
                group.Update();
                Logger.LogInfo("AddNewSpUser(): User successfully added to visitors group", "RegisterPage");

                Logger.LogInfo("AddNewSpUser(): Updating web", "RegisterPage");
                web.Update();
                Logger.LogInfo("AddNewSpUser(): Web updated", "RegisterPage");
            }
            catch(Exception ex)
            {
                Logger.LogInfo("AddNewSpUser(): Common error occured during user adding process", "RegisterPage");
                Logger.LogException(ex);
            }
            web.AllowUnsafeUpdates = false;
            site.AllowUnsafeUpdates = false;
        }       
    }
}